import React, { useState, useEffect } from 'react';
import { Routes, Route, Link, Navigate, useNavigate, useLocation } from 'react-router-dom';
import Dashboard from './components/Dashboard';
import VideoGridPage from './pages/VideoGridPage';
import ChannelPage from './pages/ChannelPage';
import VideoAdminPage from './pages/VideoAdminPage';
import LoginPage from './pages/LoginPage';
import RegisterPage from './pages/RegisterPage';
import './App.css';
import AdminDashboard from './pages/AdminDashboard';
import ConfigPage from './pages/ConfigPage';
import UserPage from './pages/UserPage';
import CameraPage from './pages/CameraPage';
import LabelPage from './pages/LabelPage';
import {
  Layout,
  Menu,
  Dropdown,
  Avatar,
  Button,
  Space,
  Typography
} from 'antd';
import {
  VideoCameraOutlined, // 替换VideoIcon
  PictureOutlined,     // 替换ImageIcon
  HomeOutlined,
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
  KeyOutlined,
  PlusOutlined,
  DashboardOutlined
} from '@ant-design/icons';

const { Header, Content } = Layout;
const { Title } = Typography;

function App() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const location = useLocation();

  // 检查用户登录状态
  useEffect(() => {
    const savedUser = localStorage.getItem('user');
    if (savedUser) {
      setUser(JSON.parse(savedUser));
    }
    setLoading(false);
  }, []);

  // 处理用户登录
  const handleLogin = (userData) => {
    setUser(userData);
    localStorage.setItem('user', JSON.stringify(userData));
  };

  // 处理用户登出
  const handleLogout = () => {
    setUser(null);
    localStorage.removeItem('user');
  };

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  const isAdminRoute = location.pathname.startsWith('/admin');

  // 重构 renderUserMenu 为符合 Ant Design v5 的配置对象
  const userMenuProps = {
    items: [
      user?.role === 'admin' && {
        key: 'admin',
        icon: <SettingOutlined />,
        label: <Link to="/admin">后台管理</Link>,
      },
      {
        key: 'switch',
        icon: <KeyOutlined />,
        label: (
          <button 
            onClick={() => {
              handleLogout();
              navigate('/login');
            }}
            style={{ width: '100%', textAlign: 'left', border: 'none', background: 'none', cursor: 'pointer' }}
          >
            切换账号
          </button>
        ),
      },
      {
        key: 'logout',
        icon: <LogoutOutlined />,
        label: (
          <button 
            onClick={handleLogout}
            style={{ width: '100%', textAlign: 'left', border: 'none', background: 'none', cursor: 'pointer' }}
          >
            退出登录
          </button>
        ),
      },
    ].filter(Boolean), // 过滤掉 null/undefined 值
  };

  return (
    <Layout className="app-layout" style={{ minHeight: '100vh' }}>
      {/* 在/admin路由下隐藏顶部导航栏，但保留header结构 */}
      {!isAdminRoute && (
        <Header className="header" style={{ padding: 0, background: '#fff', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 24px', height: '64px' }}>
            <div className="logo" style={{ display: 'flex', alignItems: 'center' }}>
              <DashboardOutlined style={{ fontSize: '24px', color: '#1890ff', marginRight: '12px' }} />
              {/* 使用环境变量获取应用名称 */}
              <Title level={3} style={{ margin: 0, color: '#1890ff' }}>
                {import.meta.env.VITE_APP_NAME || '视频监控中心'}
              </Title>
            </div>
            
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Menu
                mode="horizontal"
                selectedKeys={[location.pathname]}
                style={{ borderBottom: 0, marginRight: '16px' }}
                items={[
                  {
                    key: '/',
                    icon: <HomeOutlined />,
                    label: <Link to="/">仪表板</Link>,
                  },
                  {
                    key: '/videos',
                    icon: <VideoCameraOutlined />, // 使用正确的图标
                    label: <Link to="/videos">视频库</Link>,
                  },
                  {
                    key: '/channels',
                    icon: <PictureOutlined />, // 使用正确的图标
                    label: <Link to="/channels">实时画面</Link>,
                  },
                ]}
              />
              
              {user ? (
                <Dropdown menu={userMenuProps}>
                  <Space style={{ cursor: 'pointer' }}>
                    <Avatar icon={<UserOutlined />} style={{ backgroundColor: '#1890ff' }} />
                    <span style={{ marginLeft: '4px', fontWeight: '500' }}>{user.username}</span>
                  </Space>
                </Dropdown>
              ) : (
                <Space>
                  <Button type="link" onClick={() => navigate('/login')}>登录</Button>
                  <Button type="primary" icon={<PlusOutlined />}>
                    <Link to="/register" style={{ color: '#fff' }}>注册</Link>
                  </Button>
                </Space>
              )}
            </div>
          </div>
        </Header>
      )}

      <Content style={{ padding: '0px', backgroundColor: '#f0f2f5' }}>
        <div className="site-layout-content" style={{ background: '#fff', padding: '0px', minHeight: '280px', borderRadius: '8px' }}>
          <Routes>
            {/* 允许非注册用户访问主要页面 */}
            <Route path="/" element={<Dashboard onLogout={handleLogout} />} />
            <Route path="/videos" element={<VideoGridPage />} />
            <Route path="/channels" element={<ChannelPage />} />
            
            {/* 新的后台管理路由 */}
            <Route 
              path="/admin" 
              element={
                user && user.role === 'admin' 
                  ? <AdminDashboard user={user} /> 
                  : <Navigate to="/" replace />
              } 
            >
              <Route path="videos" element={<VideoAdminPage user={user} />} />
              <Route path="cameras" element={<CameraPage user={user} />} />
              <Route path="labels" element={<LabelPage user={user} />} />
              <Route path="configs" element={<ConfigPage user={user} />} />
              <Route path="users" element={<UserPage user={user} />} />
              <Route index element={<Navigate to="videos" replace />} />
            </Route>
            
            {/* 登录和注册页面重定向逻辑 */}
            <Route 
              path="/login" 
              element={user ? <Navigate to="/" replace /> : <LoginPage onLogin={handleLogin} />} 
            />
            <Route 
              path="/register" 
              element={user ? <Navigate to="/" replace /> : <RegisterPage />} 
            />
          </Routes>
        </div>
      </Content>
    </Layout>
  );
}

export default App;